/*
 * 版权所有(c)  1952110078@qq.com  2022 - 2022
 */

package com.ldc.module_login;

import android.os.Bundle;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.JsonObject;
import com.ldc.commonlibs.conatants.NumberCode;
import com.ldc.commonlibs.conatants.ParamsConstants;
import com.ldc.commonlibs.config.RouterConfig;
import com.ldc.commonlibs.ui.VMActivityBase;
import com.ldc.commonlibs.utils.ToastUtil;
import com.ldc.commonlibs.utils.ViewModelUtil;
import com.ldc.commonlibs.views.StateViewLayout;
import com.ldc.module_login.databinding.LoginActivityLoginBinding;
import com.ldc.module_login.viewmodel.LoginViewModel;

@Route(path = RouterConfig.Login.START_ENTER)
public class LoginActivity extends VMActivityBase<LoginActivityLoginBinding, LoginViewModel> {


    @Override
    protected void main(@Nullable Bundle savedInstanceState) {
        initView();
        initData();
    }

    @Override
    protected LoginActivityLoginBinding initViewBinding() {
        return LoginActivityLoginBinding.inflate(getLayoutInflater());
    }

    @Override
    protected StateViewLayout initStateViewLayout() {
        return StateViewLayout.init(this, R.id.content_view);
    }

    @Override
    protected LoginViewModel initViewModel() {
        return ViewModelUtil.create(this, LoginViewModel.class);
    }

    private void initView() {
        viewBinding.topBar.tvTitle.setText(R.string.login);
        viewBinding.btnSubmit.setOnClickListener(v -> {
            showLoadingView();
            viewModel.login("17666249655", "ldcabcf123");
        });
    }

    private void initData() {
        viewModel.getLoginData().observeForever(this::getLoginData);
    }

    private void getLoginData(JsonObject data) {
        showContentView();
        if (data == null) {
            ToastUtil.showToast(getString(R.string.login_failed));
            return;
        }
        int code = NumberCode.ERROR_CODE;
        if (data.has(ParamsConstants.code)) {
            code = data.get(ParamsConstants.code).getAsInt();
        }
        if (code == NumberCode.SUCCESS_CODE) {
            // 主页
            ARouter.getInstance()
                    .build(RouterConfig.Main.START_ENTER)
                    .navigation();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        viewModel.getLoginData().removeObserver(this::getLoginData);
    }
}